'ui';
//这里是宝图
auto.setWindowFilter(function (window) {
	return window.title == '融易抢单'
})

let storage = storages.create('rong')
// storage.clear()
let minPrice = storage.get('minPrice', '0')
let maxPrice = storage.get('maxPrice', '999')
let qch = false
let ych = false
let xch = false
let jych = false
let jhch = false
let mgch = false
let mfch = false
let lych = false

let keyCode = storage.get('keyCode', '')
let imeiKey = getImeiKey()

let active = getActiveDate()
if (active <= 0) { 
	active = 0
}

// 脚本运行线程
let workThread = null
// 脚本运行状态
let isRunning = false
// 悬浮窗口
let wd = null

events.on('exit', function () {
	storage.put('minPrice', minPrice)
	storage.put('maxPrice', maxPrice)
})

function showFloaty() {
	wd = floaty.rawWindow(
		<vertical w="*" h="*">
			<frame layout_weight="1" h="30" layout_gravity="center">
				<img
					w="*"
					h="30"
					src="#ffffff"
					borderWidth="1dp"
					scaleType="fitXY"
					circle="true"
				/>
				<text
					id="start"
					h="30"
					text="开始运行"
					textSize="12sp"
					gravity="center"
					padding="15 0 "
				/>
			</frame>
			<frame h="30" layout_weight="1" layout_gravity="center" marginTop="2">
				<img
					w="*"
					h="30"
					src="#ffffff"
					borderWidth="1dp"
					scaleType="fitXY"
					circle="true"
				/>
				<text
					id="stop"
					h="30"
					text="结束运行"
					textSize="12sp"
					gravity="center"
					padding="15 0"
				/>
			</frame>
		</vertical>
	)
	wd.setPosition(40, device.height / 2)
	wd.exitOnClose()
	wd.stop.on('click', function () {
		isRunning = false
		if (workThread) {
			workThread.interrupt()
			workThread = null
		}
		exit()
		toastLog('运行结束')
	})
	wd.start.on('click', function () {
		//程序开始运行之前判断无障碍服务
		if (!auto.service) {
			toast('请先开启无障碍服务！')
			app.startActivity({
				action: 'android.settings.ACCESSIBILITY_SETTINGS',
			})
			return
		}

		if (isRunning) {
			toastLog('运行暂停')
			isRunning = false
			ui.run(function () {
				wd.start.setText('开始运行')
			})
			// threads.shutDownAll()
			return
		}
		if (getActiveDate() > 0) { 
			toastLog('请输入激活码')
			checkAuth()
			return
		}
		isRunning = true
		ui.run(function () {
			wd.start.setText('暂停运行')
		})
		qch = ui.qch.isChecked()
		ych = ui.ych.isChecked()
		xch = ui.xch.isChecked()
		jych = ui.jych.isChecked()
		jhch = ui.jhch.isChecked()
		mgch = ui.mgch.isChecked()
		mfch = ui.mfch.isChecked()
		lych = ui.lych.isChecked()

		if (!workThread) {
			workThread = threads.start(function () {
				toastLog('运行开始')
				app.launchApp('融易抢单')
				while (true) {
					try {
						if (getActiveDate() > 0) { 
							toastLog('请输入激活码')
							exit()
						}
						while (!isRunning) { }
						if (currentPackage() != 'com.congrong.qianduoduo') { 
							app.launchApp('融易抢单')
							sleep(2000)
						}
						home()
					} catch (err) {
						console.log(err)
						while (
							currentPackage() == 'com.congrong.qianduoduo' &&
							!text('刷新订单列表').exists()
						) {
							back()
							sleep(1000)
						}
						toast('请检查余额')
						// exit()
					}
				}
			})
		}
	})
}

threads.start(function () {
	// // 检测是否打开无障碍权限
	// if (!floaty.checkPermission()) {
	// 	floaty.requestPermission()
	// 	exit()
	// }
	// sleep(1000)
	showFloaty()
})


ui.statusBarColor('#40a5f3')
ui.layout(
	<vertical>
		<appbar bg="#40a5f3">
			<toolbar id="title" title="融易抢单辅助v2" />
		</appbar>
		<Switch
			id="floatx"
			text="悬浮窗权限"
			checked="{{floaty.checkPermission()}}"
			padding="8 8 8 8"
			textSize="15sp"
			gravity="right"
		/>
		<Switch
			id="autoService"
			text="无障碍服务"
			checked="{{auto.service != null}}"
			padding="8 8 8 8"
			textSize="15sp"
			gravity="right"
		/>
		<vertical paddingLeft="40dp">
			<horizontal>
				<checkbox id="qch" text="其他贷款"/>
				<checkbox marginLeft="20" id="ych" text="医疗贷款"/>
			</horizontal>
			<horizontal>
				<checkbox id="xch" text="消费贷款"/>
				<checkbox marginLeft="20" id="jych" text="教育贷款"/>
			</horizontal>
			<horizontal>
				<checkbox id="jhch" text="结婚贷款"/>
				<checkbox marginLeft="20"  id="mgch" text="买购车贷"/>
			</horizontal>
			<horizontal>
				<checkbox id="mfch" text="买房贷款"/>
				<checkbox marginLeft="20" id="lych" text="旅游贷款"/>
			</horizontal>
			<horizontal>
				<text text="金额下限(万元):" marginRight="10" />
				<input
					id="minPrice"
					text="{{minPrice}}"
					textSize="14sp"
					inputType="number"
					w="80dp"
					gravity="center"
				/>
			</horizontal>
			<horizontal>
				<text text="金额上限(万元):" marginRight="10" />
				<input
					id="maxPrice"
					text="{{maxPrice}}"
					textSize="14sp"
					inputType="number"
					w="80dp"
					gravity="center"
				/>
			</horizontal>
		</vertical>
	</vertical>
)

ui.minPrice.addTextChangedListener({
	afterTextChanged: function (content) {
		content = content.toString().trim()
		if (content.length == 0) {
			content = 0
		}
		minPrice = Number(content)
	},
})
ui.maxPrice.addTextChangedListener({
	afterTextChanged: function (content) {
		content = content.toString().trim()
		if (content.length == 0) {
			content = 999
		}
		if (content < minPrice) {
			content = minPrice
		}
		maxPrice = Number(content)
	},
})

ui.floatx.on('click', function (checked) {
	floaty.requestPermission()
})
ui.autoService.on('check', function (checked) {
	// 用户勾选无障碍服务的选项时，跳转到页面让用户去开启
	if (checked && auto.service == null) {
		app.startActivity({
			action: 'android.settings.ACCESSIBILITY_SETTINGS',
		})
	}
	if (!checked && auto.service != null) {
		auto.service.disableSelf()
	}
})

// 当用户回到本界面时，resume事件会被触发
ui.emitter.on('resume', function () {
	// 此时根据无障碍服务的开启情况，同步开关的状态
	ui.floatx.checked = floaty.checkPermission()
	ui.autoService.checked = auto.service != null
})

ui.emitter.on('back_pressed', function (event) {
	if (workThread && workThread.isAlive()) {
		event.consumed = true
	}
})


function checkAuth() { 
	return
	let view = ui.inflate(
		<vertical padding="16 0">
			<text id="cImei" text="复制设备标识码" textColor="#40a5f3" gravity="right"/>
			<input id="mkey" textSize="12sp"/>
		</vertical>
		, null, false);
	view.cImei.on('click', function () { 
		setClip(imeiKey)
		toastLog('复制成功')
	})
	
	// 显示对话框
	dialogs.build({
		customView: view,
		title: "请输入激活码",
		positive: "激活",
		// negative: "取消",
		// view高度超过对话框时是否可滑动
		wrapInScrollView: false,
		// 按下按钮时是否自动结束对话框
		autoDismiss: false
	}).on("positive", (dialog) => {
		let mkey = String(view.mkey.getText())
		keyCode = mkey
		let act = getActiveDate()
		if (act <= 0) {
			keyCode = ''
			storage.put('keyCode', '')
			if (workThread) { 
				workThread.interrupt()
			}
			view.mkey.setError("激活码错误");
		} else {
			active = act
			storage.put('keyCode', keyCode)
			ui.run(() => { 
				ui.title.setTitle('融易抢单辅助 剩余' + active +'天')
			})
			toast("激活成功");
			dialog.dismiss();
		}
	}).on("negative", (dialog) => {
		dialog.dismiss();
	}).show();
}

function getImeiKey() {
	let imei = device.getIMEI()||''
	if (imei.length <= 0 || !imei) {
		console.log('imei is null')
		throw '请授予权限'
	} else {
		imei = $crypto.digest(' + ' + imei, 'SHA-1')
    }
	return imei
}

function getActiveDate() { 
	if (keyCode.length == 0) { 
		return -1
	}
    importClass(java.text.SimpleDateFormat)
    importClass(java.util.Calendar)
    let calendar = Calendar.getInstance()
    sdf = new SimpleDateFormat('yyMMdd')
    for (let i = 0; i <= 30; i++) { 
        let date = sdf.format(calendar.getTime())
        let mkey = createKeyCode(imeiKey,date)
        if (mkey == keyCode) { 
            return i
        }
        calendar.add(Calendar.DATE, 1);
    }
    return -1
}

function createKeyCode(imeiKey,deadline) {
	let message = parseInt(deadline) * 3 - 8 + imeiKey
	let aesKey = new $crypto.Key('=u=口你🐔八')
	let aes = $crypto.encrypt(message, aesKey, 'AES/ECB/PKCS5padding')
	let keyCode = $crypto.digest($base64.encode(aes) + 'rong', 'MD5').toString()
	return keyCode
}

function home() {
	if (!text('全部订单').exists()) return
	text('刷新订单列表').findOne(3000).click()
	sleep(500)
	// text('可抢订单').findOne(1000).click()
	if (!textContains('可抢单').visibleToUser().exists()) {
		text('刷新订单列表').findOne(3000).click()
		sleep(1000)
		return
	}
	// textContains('可抢单').visibleToUser().findOne(1000).click()
	let nodes = textContains('可抢单').visibleToUser().find()
	let isClicked = false
	for (let item of nodes) {
		let text = item.text()
		if (!qch && text.match(/其他贷款/gm)) { 
			continue
		}
		if (!ych && text.match(/医疗贷款/gm)) { 
			continue
		}
		if (!xch && text.match(/消费贷款/gm)) { 
			continue
		}


		if (!jych && text.match(/教育贷款/gm)) { 
			continue
		}
		if (!jhch && text.match(/结婚贷款/gm)) { 
			continue
		}
		if (!mgch && text.match(/买购车贷/gm)) { 
			continue
		}
		if (!mfch && text.match(/买房贷款/gm)) { 
			continue
		}
		if (!lych && text.match(/旅游贷款/gm)) { 
			continue
		}
		





		let ms = text.match(/\d+\.0万/g)
		if (ms == null) {
			continue
		}
		let mPrice = Number(ms[0].split('.')[0])
		if (mPrice >= minPrice && mPrice <= maxPrice) {
			item.click()
			isClicked = true
			break
		}
	}

	if (!isClicked) {
		sleep(1000)
		text('刷新订单列表').findOne(3000).click()
		sleep(1000)
		return
	}

	text('资产信息').findOne(3000)
	if (text('立即抢单').exists()) {
		text('立即抢单').findOne(10000).click()
		text('抢单').findOne(10000).click()
	}
	if (!text('已抢单').findOne(500)) {
		throw '余额不足'
	}
	back()
	// text('刷新订单列表').findOne(3000).click()
}

